const MAX_CONCURRENT = 3 // 最大并发数
const RETRY_LIMIT = 3   // 重试次数

import axios from 'axios';
class UploadQueue {
  constructor(fileHash, chunks, file, chunkSize, uploadId, uploadedChunks, token, start) {
    this.fileHash = fileHash
    this.token = token;
    this.chunks = chunks
    this.uploadedChunks = uploadedChunks
    this.queue = chunks.map((chunk, index) => ({
      chunk,
      index: index + start,
      file,
      fileHash,
      chunkSize,
      uploadId,
      retries: 0,
      status: uploadedChunks.includes(index + start) ? 'done' : 'pending'
    }))
    this.activeCount = 0
  }

  async process() {
    while (this.queue.length > 0 && this.activeCount < MAX_CONCURRENT) {
      const task = this.queue.find(t => t.status === 'pending')
      // console.log('queue', this.queue, task)
      if (!task) break

      this.activeCount++
      task.status = 'uploading'
      
      try {
        await this.uploadChunk(task)
        task.status = 'done'
        self.postMessage({ type: 'CHUNK_DONE', payload: { index: task.index } })
      } catch (error) {
        if (task.retries < RETRY_LIMIT) {
          task.retries++
          task.status = 'pending'
        } else {
          self.postMessage({ type: 'ERROR', payload: error })
        }
      }
      
      this.activeCount--
      this.updateProgress()
      this.process()
    }
    
    if (this.queue.every(t => t.status === 'done')) {
      // await this.mergeChunks()
      self.postMessage({ type: 'COMPLETE' })
    }
  }

  async uploadChunk(task) {
    const formData = new FormData()
    formData.append('file', task.chunk, `${task.file.name}.part${task.index}`)
    formData.append('fileHash', task.fileHash)
    formData.append('chunkIndex', task.index)
    formData.append('chunkSize', task.chunkSize)
    formData.append('uploadId', task.uploadId)
    let VITE_APP_BASE_API = '/dev-api';
    if (import.meta.env.MODE === 'production') {
      VITE_APP_BASE_API = '/prod-api';
    }
    if (import.meta.env.MODE === 'green') {
      VITE_APP_BASE_API = '/isfd-api';
    }
    // const response = await fetch(`${VITE_APP_BASE_API}/isfd/largeFile/chunks/upload`, {
    //   method: 'POST',
    //   body: formData,
    //   headers: { 'Content-Type': 'multipart/form-data', 'Authorization': 'Bearer ' + getToken() }
    // })
    // let token = window.localStorage.getItem('Admin-Token') || ''
    // console.log('token', this.token)
    const clientId = import.meta.env.VITE_APP_CLIENT_ID;
    const response = await axios.post(`${VITE_APP_BASE_API}/isfd/largeFile/chunks/upload`, formData, {
      headers: { 'Content-Type': 'multipart/form-data', 'Authorization': 'Bearer ' + this.token, 'clientId': clientId }
    })
    // .then(res => {
    //   console.log('res===', res)
    //   if (res.data.code == 200) {
    //     task.status = 'done'
    //     self.postMessage({ type: 'CHUNK_DONE', payload: { index: task.index } })
    //   }
    // }).catch((err) => {
    //   throw new Error(`分片上传失败: ${task.index}`)
    // })
    // const response = await op2ChunksUpload(formData);
    // console.log('response', response)
    if (!response || response.data.code != 200) throw new Error(`分片上传失败: ${task.index}`)
  }

  updateProgress() {
    const doneCount = this.queue.filter(t => t.status === 'done').length
    const progress = Math.floor((doneCount / this.chunks.length) * 100)
    console.log('progress',progress, this.queue.map(t =>t.status))
    self.postMessage({ type: 'PROGRESS', payload: { progress } })
  }

  async mergeChunks() {
    await fetch('/api/merge', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ hash: this.fileHash })
    })
  }
}

self.onmessage = async (e) => {
  const { type, payload } = e.data
  if (type === 'START_UPLOAD') {
    const queue = new UploadQueue(
      payload.fileHash,
      payload.chunks,
      payload.file,
      payload.chunkSize,
      payload.uploadId,
      payload.uploadedChunks,
      payload.token,
      payload.start
    )
    queue.process()
  }
}
